package com.wxtf.platform.main.contraceptives;

import java.util.ArrayList;
import java.util.List;  
import javax.servlet.http.HttpServletRequest; 
import net.sf.json.JSONArray;
import net.sf.json.JSONObject; 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 
import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.FormatUtil;

public class TmaApplyMainAction extends LogicBase implements CommonsCallProvider  {

	private static Log log = LogFactory.getLog(TmaApplyMainAction.class);

	public TmaApplyMainAction(String jsonArray) {

	}

	String[] fields = {"tmaam_id","org_id","tmaam_code","tmaam_person","tmaam_time","tmaam_status","tmaam_content","tmaam_memo",
			"reserve1","reserve2","reserve3","reserve4","reserve5","create_by","create_time","last_modify_by","last_modify_time"
	};
	String[] fields2 = {"tmaad_id","tmaam_id","tmad_id","tmaad_num",
			"reserve1","reserve2","reserve3","reserve4","reserve5","create_by","create_time","last_modify_by","last_modify_time"
	};
	/** 
	 * 描述：delete 删除记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @author sun_xiaoliang  
	 */
	@Override
	public Object delete(Object jsonArray) throws Exception { 
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		
		id = id.replace(",", "','");
		List<String> list = new ArrayList<String>(); 	 
		list.add("delete from tma_apply_detail where tmaam_id in ('"+ id +"')  and  tmaam_id not in (select tmaam_id from tma_apply_main where tmaam_status<>1 and tmaam_status<>2) ");
		list.add("delete from tma_apply_main where tmaam_id in ('"+ id +"')  and (tmaam_status=1 or tmaam_status=2) ");
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"删除成功\"";
	}
 
	/** 
	 * 描述：insert 增加记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @author sun_xiaoliang
	 */
	@Override
	public Object insert(Object jsonArray) throws Exception {		
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String tmaam_code = jsonObject.getString("tmaam_code");
		sql = "select count(*) from tma_apply_main where tmaam_code=?";
		List<Object> ls = AccessDataBaseUtil.query4List(sql,new Object[]{tmaam_code});
		int hasId = Integer.parseInt(ls.get(0).toString());
		if (hasId > 0) { 
			return "{\"result\":false,\"resultmessage\":\"\",\"resultrecord\":\"申领编号不能重复\"}";
		}
		UserBean user = (UserBean) (this.getRequest()).getSession().getAttribute("userBean");
		String create_by = user.getUserId();
		String create_time = FormatUtil.getCurentDate();
		String tmaam_id = AccessDataBaseUtil.getPKUUID();
		List<String> list = new ArrayList<String>();  
		StringBuffer buff = new StringBuffer("insert into tma_apply_main(tmaam_id,org_id,tmaam_person,tmaam_code,tmaam_time,tmaam_status,create_by,create_time,last_modify_by,last_modify_time) values(");
		buff.append("'").append(tmaam_id).append("'")
		.append(",'").append(jsonObject.getString("org_id")).append("'")
		.append(",'").append(jsonObject.getString("tmaam_person")).append("'")
		.append(",'").append(tmaam_code).append("'")
		.append(",'").append(jsonObject.getString("tmaam_time")).append("'")
		.append(",'").append(jsonObject.getString("tmaam_status")).append("'")
		.append(",'").append(create_by).append("'")
		.append(",'").append(create_time).append("'")
		.append(",'").append(create_by).append("'")
		.append(",'").append(create_time).append("')");
		list.add(buff.toString());
		buff.setLength(0);
		String ids = jsonObject.getString("ids");
		array = JSONArray.fromObject(ids);
		
		 for (int i=0;i<array.size();i++){
		 	jsonObject = JSONObject.fromObject(array.getString(i)); 
			buff.append("insert into tma_apply_detail(tmaad_id,tmaam_id,tmad_id,tmaad_num,create_by,create_time,last_modify_by,last_modify_time) values(")
			.append("'").append(AccessDataBaseUtil.getPKUUID()).append("'")
			.append(",'").append(tmaam_id).append("'")
			.append(",'").append(jsonObject.getString("tmad_id")).append("'")
			.append(",'").append(jsonObject.getString("tmaad_num")).append("'")
			.append(",'").append(create_by).append("'")
			.append(",'").append(create_time).append("'")
			.append(",'").append(create_by).append("'")
			.append(",'").append(create_time).append("')");
			list.add(buff.toString());
			buff.setLength(0);
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"新建成功\"";
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		// TODO Auto-generated method stub
		return null;	
	}

	/** 
	 * 描述：select 查询记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @author sun_xiaoliang  
	 */
	@Override
	public Object select(Object jsonArray) throws Exception {
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean");
		String CurOrgId = user.getCurOrgId();
		sql = " from tma_apply_main o,t_user u,t_department d , t_department d2 where o.create_by=u.user_id and o.org_id=d.department_id and d.DPARENT_ID=d2.DEPARTMENT_ID and o.org_id='"+CurOrgId+"' order by tmaam_status ,tmaam_code desc ";
		String countSql = "select count(tmaam_id) " + sql;
		String querySql = "select tmaam_id,d.caption as org_id,tmaam_code,tmaam_time,   tmaam_status   ,u.caption as create_by,d.CAPTION,d2.CAPTION as CAPTION2,tmaam_person ,tmaam_status,tmaam_content,tmaam_memo,reserve1, create_by,create_time,last_modify_by,last_modify_time" + sql;
		String[] fields = {"tmaam_id","org_id","tmaam_code","tmaam_time","tmaam_status","create_by","CAPTION","CAPTION2","tmaam_person", "tmaam_status","tmaam_content","tmaam_memo","reserve1", "create_by","create_time","last_modify_by","last_modify_time"};
		return AccessDataBaseUtil.query4SQLPagging(fields, countSql, querySql, this.getPage(), this.getPagesize(), null);
	} 
	
	@Override
	public Object run() {
		Object msg = "";
		try {
			if ("queryPage".equals(this.getMethodName())) {// 列表
				msg = this.select(this.getLogicData());
				return msg.toString();
			} else if ("update".equals(this.getMethodName())) {// 修改
				msg = this.update(this.getLogicData());
			} else if ("save".equals(this.getMethodName())) {// 添加
				msg = this.insert(this.getLogicData());
			} else if ("delete".equals(this.getMethodName())) {// 删除
				msg = this.delete(this.getLogicData());
			} else if ("updateBatch".equals(this.getMethodName())) {// 删除
				msg = this.updateBatch(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}
			if (msg == null || "[null]".equals(msg)) {
				msg = "\"\"";
			}
			if(msg.toString().startsWith("{") || msg.toString().startsWith("[")){
				return msg;
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString()); 
		} catch (Exception e) {
			msg = "操作失败，请联系管理员";
			msg = ConstantInfoHelper.generateJSONString(ConstantInfoHelper.JSON_HEAD, ConstantInfoHelper.getFailResultDetail(msg.toString()), false);
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}
 
	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	} 

	/** 
	 * 描述：update 更新记录
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @author sun_xiaoliang  
	 */
	@Override
	public Object update(Object jsonArray) throws Exception {
 
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0)); 
		UserBean user = (UserBean)(this.getRequest()).getSession().getAttribute("userBean"); 
		String tmaam_code = jsonObject.getString("tmaam_code");
		sql = "select count(*) from tma_apply_main where tmaam_code=? and tmaam_code<>'"+tmaam_code+"'";
		List<Object> ls = AccessDataBaseUtil.query4List(sql,new Object[]{tmaam_code});
		int hasId = Integer.parseInt(ls.get(0).toString());
		if (hasId > 0) { 
			return "{\"result\":false,\"resultmessage\":\"\",\"resultrecord\":\"申领编号不能重复\"}";
		}
 
		String tmaam_id = jsonObject.getString("tmaam_id");
		String create_by = user.getUserId();
		String create_time = FormatUtil.getCurentDate();
		List<String> list = new ArrayList<String>();
		StringBuffer buff = new StringBuffer();
		buff.append("update tma_apply_main set ");
		Object[] obj = new Object[fields.length];

		for (int j = 1; j < fields.length; j++) {
			obj[j] = jsonObject.getString(fields[j]);
		}
		obj[fields.length - 2] = create_by;
		obj[fields.length - 1] = create_time;
		for (int j = 1; j < fields.length; j++) {
			if(fields.length - j == 3 || fields.length - j == 4) {
			} else {
				buff.append(fields[j]).append("='").append(obj[j]).append("',");
			}
		}
		buff.deleteCharAt(buff.length() - 1).append(" where tmaam_id =  '" +jsonObject.getString("tmaam_id")).append("'");
		list.add(buff.toString());
		buff.setLength(0);
		String ids = jsonObject.getString("ids");
		array = JSONArray.fromObject(ids); 	 
		for (int i=0;i<array.size();i++){
			jsonObject = JSONObject.fromObject(array.getString(i)); 
			String tmaad_id = jsonObject.getString("tmaad_id");
			if(tmaad_id.length() == 32) {  
				buff.append("update tma_apply_detail set ") 
				.append("tmad_id='").append(jsonObject.getString("tmad_id")).append("'")
				.append(",tmaad_num='").append(jsonObject.getString("tmaad_num")).append("'") 
				.append(" where tmaad_id='"+ tmaad_id +"'");
			} else { 
				buff.append("insert into tma_apply_detail(tmaad_id,tmaam_id,tmad_id,tmaad_num,create_by,create_time,last_modify_by,last_modify_time) values(")
				.append("'").append(AccessDataBaseUtil.getPKUUID()).append("'")
				.append(",'").append(tmaam_id).append("'")
				.append(",'").append(jsonObject.getString("tmad_id")).append("'")
				.append(",'").append(jsonObject.getString("tmaad_num")).append("'")
				.append(",'").append(create_by).append("'")
				.append(",'").append(create_time).append("'")
				.append(",'").append(create_by).append("'")
				.append(",'").append(create_time).append("')"); 
			}
			list.add(buff.toString());
			buff.setLength(0);
		}
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"保存成功\"";
	}
	
	 
	/** 
	 * 描述：updateBatch 冲红更新
	 * @param jsonArray
	 * @return
	 * @throws Exception
	 * @author sun_xiaoliang
	 */
	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String id = jsonObject.getString("ids");
		List<String> list = new ArrayList<String>(); 	
		list.add("update tma_apply_main set tmaam_status=3 where tmaam_id = '" + id + "'");
		list.add("update tma_income_main set tmaim_is_valid=1 where tmaim_id = '" + id + "'");
		list.add("update tma_outcome_main set TMAOM_IS_VALID=1 where TMAOM_ID = '" + id + "'");
		AccessDataBaseUtil.executeSQLUpdate(list);
		return "\"冲红成功\""; 
	}

	@Override
	public Object onCreate(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object onInit(Object jsonArray) {
		// TODO Auto-generated method stub
		return null;
	}

}
